package com.piece.mall.config;

import com.piece.core.rabbit.config.RabbitAutoConfig;
import com.piece.mall.api.constant.MallRegisterConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Slf4j
@Configuration
@ConditionalOnClass(RabbitAutoConfig.class)
public class RabbitMallConfig {

    /**
     * 交换机（延迟队列）
     */
    @Bean("orderDelayExchange")
    public TopicExchange orderDelayExchange() {
        return new TopicExchange(MallRegisterConstants.ORDER_DELAY_EXCHANGE_NAME, true, false);
    }

    /**
     * 延时队列
     */
    @Bean(name = "orderDelayQueue")
    public Queue orderDelayQueue() {
        HashMap<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", MallRegisterConstants.ORDER_DLX_EXCHANGE_NAME);
        arguments.put("x-dead-letter-routing-key", MallRegisterConstants.ORDER_RELEASE_ROUTE_NAME);
        arguments.put("x-message-ttl", 1800000); //消息30分钟后过期
        return new Queue(MallRegisterConstants.ORDER_DELAY_QUEUE_NAME, true, false, false, arguments);
    }

    /**
     * 绑定延迟队列和交换机
     */
    @Bean
    public Binding registerOrderCreateBinding(TopicExchange orderDelayExchange, Queue orderDelayQueue) {
        return BindingBuilder
                .bind(orderDelayQueue)
                .to(orderDelayExchange)
                .with(MallRegisterConstants.ORDER_CREATE_ROUTE_NAME);
    }

    /**
     * 交换机（死信队列）
     */
    @Bean(name = "orderDlxExchange")
    public DirectExchange orderDlxExchange() {
        return new DirectExchange(MallRegisterConstants.ORDER_DLX_EXCHANGE_NAME, true, false);
    }

    @Bean(name = "orderDlxQueue")
    public Queue orderDlxQueue() {
        return new Queue(MallRegisterConstants.ORDER_DLX_QUEUE_NAME, true, false, false);
    }

    /**
     * 绑定死信队列和交换机
     */
    @Bean
    public Binding registerOrderReleaseBinding(DirectExchange orderDlxExchange, Queue orderDlxQueue) {
        return BindingBuilder
                .bind(orderDlxQueue)
                .to(orderDlxExchange)
                .with(MallRegisterConstants.ORDER_RELEASE_ROUTE_NAME);
    }

    /**
     * 秒杀订单队列（削峰）
     */
    @Bean(name = "orderSecKillQueue")
    public Queue orderSecKillQueue() {
        Queue queue = new Queue(MallRegisterConstants.ORDER_SECKILL_QUEUE_NAME, true, false, false);
        return queue;
    }

    /**
     * 绑定：交换机与秒杀订单
     */
    @Bean
    public Binding orderSecKillOrderQueueBinding(TopicExchange orderDelayExchange, Queue orderSecKillQueue) {
        return BindingBuilder
                .bind(orderSecKillQueue)
                .to(orderDelayExchange)
                .with(MallRegisterConstants.ORDER_SECKILL_ROUTE_NAME);
    }
}
